package com.etoak.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.nacos.shaded.com.google.common.collect.Maps;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.jwt.MyJwtUtil;
import com.etoak.common.redis.service.RedisService;
import com.etoak.dto.LoginDto;
import com.etoak.entity.User;
import com.etoak.mapper.UserMapper;
import com.etoak.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.TokenVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-08-27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RedisService redisService;

    @Override
    public TokenVo login(LoginDto loginDto) {
        /* 1、验证 code */
        //得到code
        String code = redisService.get(CommonConstant.CODE_KEY_PREFIX + loginDto.getUuid());
        if(!StringUtils.equalsIgnoreCase(code,loginDto.getCode())){
            throw new CustomException("验证码错误 ");
        }
        /* 2、验证 username、password */
        String password = MD5.create().digestHex(loginDto.getPassword());
        User user = lambdaQuery().eq(User::getUsername, loginDto.getUsername())
                .eq(User::getPassword, password)
                .one();
        if(ObjectUtils.isEmpty(user)){
            throw  new CustomException("用户名或者密码错误");
        }
        /* 3、创建 JWT */
        Map<String,Object> claimsMap = Maps.newHashMap();
        claimsMap.put("id",user.getId());
        claimsMap.put("username",user.getUsername());
        String token = MyJwtUtil.create(claimsMap);
        return new TokenVo(user.getUsername(),token);
    }
}
